﻿using System;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

/// <summary>
/// 百度UEditor编辑器asp.net上传组件
/// buzhizhe 
/// 2011.10.21
/// </summary>

public partial class ueditor_dialogs_image_upload : System.Web.UI.Page
{
    public string url;
    private string _uploadPath = "uploadfiles/"; //上传文件保存路径
    private int _FileSizeMax = 1000; //上传文件最大限制（单位kb）

    protected void Page_Load(object sender, EventArgs e)
    {
        url = Request.QueryString["url"];
        string strPath = Request.QueryString["path"];
        if (strPath != null && strPath != "") _uploadPath = strPath; //从外部获取图片保存路径

        if (Request.Files.Count > 0)
        {
            if (!AllowUpload())
            {
                Response.Write("<script type='text/javascript'>alert('对不起，系统没有开启上传权限。');location.href='upload.aspx'</script>");
                Response.End();
            }

            uploadfile();
        }
    }

    /// <summary>
    /// 上传文件到服务器
    /// </summary>
    private void uploadfile()
    {
        HttpPostedFile file = Request.Files[0];
        if (file.ContentType.IndexOf("image") < 0)
        {
            Response.Write("<script type='text/javascript'>alert('非法的图片格式！');location.href='upload.aspx'</script>");
            Response.End();
        }
        if (file.ContentLength > _FileSizeMax * 1024)
        {
            Response.Write("<script type='text/javascript'>alert('图片大小超出" + _FileSizeMax + "KB限制，请重新选择！');location.href='upload.aspx'</script>");
            Response.End();
        }
        string fileExt = Path.GetExtension(file.FileName);
        string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + (new Random()).Next(1, 99);
        string fullFileName = _uploadPath + fileName + fileExt;
        string savePath = Server.MapPath(".") + "/" + fullFileName;
        file.SaveAs(savePath);

        Response.Write("<script type='text/javascript'>parent.reloadImg('" + fullFileName + "');</script>");
        Response.Write("<script type='text/javascript'>location.href='upload.aspx?url=" + fullFileName + "'</script>");
        Response.End();
    }

    /// <summary>
    /// 判定系统是否允许上传，建议用session判定
    /// </summary>
    /// <returns>返回true则允许上传，false则不允许上传</returns>
    private bool AllowUpload()
    {
        #region validate login
        BZZ.CommonFunctions cf = new BZZ.CommonFunctions();
        if (!cf.isLogin(this.Request))
        {

            Response.Write(cf.doneFailed("登录超时，请重新登录后台。", "login.aspx"));
            //Response.End();
        }

        #endregion
        ///请在此处写入判断代码
        return true;
    }


}
